Page({
  data: {
    searchValue: '',
    activeTab: 0,
    tabs: [
      { label: '全部', value: 0 },
      { label: '日常照料', value: 1 },
      { label: '医疗护理', value: 2 },
      { label: '康复训练', value: 3 },
      { label: '心理慰藉', value: 4 },
      { label: '文娱活动', value: 5 },
      { label: '营养餐饮', value: 6 }
    ],
    sortType: 'default', // default, price, rating
    sortOrder: 'desc', // asc, desc
    loading: true,
    serviceList: []
  },
  
  onLoad(options) {
    // 获取页面参数
    if (options.keyword) {
      this.setData({ searchValue: options.keyword })
    }
    
    if (options.category) {
      // 根据分类名称设置当前标签页
      const categoryIndex = this.data.tabs.findIndex(tab => tab.label === options.category)
      if (categoryIndex !== -1) {
        this.setData({ activeTab: categoryIndex })
      }
    }
    
    // 加载服务列表数据
    this.loadServiceList()
  },
  
  // 加载服务列表数据
  loadServiceList() {
    this.setData({ loading: true })
    
    // 模拟数据，实际项目中应该从云数据库获取
    setTimeout(() => {
      const serviceList = [
        {
          _id: 'service001',
          name: '专业护理服务',
          description: '由专业护理人员提供的居家照护服务，包括生活照料、健康监测等',
          image: '/images/services/nursing.jpg',
          price: 150,
          unit: '小时',
          rating: 4.8,
          tags: ['专业', '上门', '认证'],
          category: '医疗护理'
        },
        {
          _id: 'service002',
          name: '老年人康复训练',
          description: '针对老年人的专业康复训练，提高身体机能，预防功能退化',
          image: '/images/services/rehabilitation.jpg',
          price: 200,
          unit: '次',
          rating: 4.7,
          tags: ['专业', '一对一', '康复'],
          category: '康复训练'
        },
        {
          _id: 'service003',
          name: '营养餐配送',
          description: '专为老年人定制的营养均衡餐食，按需配送到家',
          image: '/images/services/meal.jpg',
          price: 50,
          unit: '餐',
          rating: 4.5,
          tags: ['营养', '配送', '定制'],
          category: '营养餐饮'
        },
        {
          _id: 'service004',
          name: '日常生活照料',
          description: '提供老年人日常生活照料服务，包括洗漱、穿衣、进食等基本生活照料',
          image: '/images/services/daily_care.jpg',
          price: 120,
          unit: '小时',
          rating: 4.6,
          tags: ['贴心', '上门', '全天候'],
          category: '日常照料'
        },
        {
          _id: 'service005',
          name: '老年心理咨询',
          description: '专业心理咨询师提供一对一心理疏导和情感支持服务',
          image: '/images/services/psychological.jpg',
          price: 180,
          unit: '次',
          rating: 4.9,
          tags: ['专业', '一对一', '隐私保护'],
          category: '心理慰藉'
        }
      ]
      
      // 根据当前标签页筛选数据
      let filteredList = serviceList
      if (this.data.activeTab !== 0) {
        const category = this.data.tabs[this.data.activeTab].label
        filteredList = serviceList.filter(item => item.category === category)
      }
      
      // 根据搜索关键词筛选
      if (this.data.searchValue) {
        const keyword = this.data.searchValue.toLowerCase()
        filteredList = filteredList.filter(item => 
          item.name.toLowerCase().includes(keyword) || 
          item.description.toLowerCase().includes(keyword) ||
          item.tags.some(tag => tag.toLowerCase().includes(keyword))
        )
      }
      
      // 根据排序类型和顺序排序
      if (this.data.sortType !== 'default') {
        filteredList.sort((a, b) => {
          const factor = this.data.sortOrder === 'asc' ? 1 : -1
          return factor * (a[this.data.sortType] - b[this.data.sortType])
        })
      }
      
      this.setData({
        serviceList: filteredList,
        loading: false
      })
    }, 500)
    
    // 实际项目中的云数据库查询示例
    /*
    const db = wx.cloud.database()
    const _ = db.command
    
    // 构建查询条件
    let query = {}
    
    // 根据标签页筛选分类
    if (this.data.activeTab !== 0) {
      const category = this.data.tabs[this.data.activeTab].label
      query.category = category
    }
    
    // 根据搜索关键词筛选
    if (this.data.searchValue) {
      const keyword = this.data.searchValue
      query = _.or([
        { name: db.RegExp({ regexp: keyword, options: 'i' }) },
        { description: db.RegExp({ regexp: keyword, options: 'i' }) },
        { tags: keyword }
      ])
    }
    
    // 构建排序条件
    let orderBy = {}
    if (this.data.sortType !== 'default') {
      const sortField = this.data.sortType
      const sortOrder = this.data.sortOrder === 'asc' ? 1 : -1
      orderBy[sortField] = sortOrder
    }
    
    db.collection('services')
      .where(query)
      .orderBy(orderBy)
      .get()
      .then(res => {
        this.setData({
          serviceList: res.data,
          loading: false
        })
      })
      .catch(err => {
        console.error('查询服务列表失败', err)
        this.setData({ loading: false })
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      })
    */
  },
  
  // 搜索相关方法
  onSearchChange(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },
  
  onSearchSubmit(e) {
    const searchValue = e.detail.value
    this.setData({ searchValue })
    this.loadServiceList()
  },
  
  // 标签页切换事件
  onTabsChange(e) {
    this.setData({
      activeTab: e.detail.value
    })
    this.loadServiceList()
  },
  
  // 排序方式切换事件
  onSortChange(e) {
    const type = e.currentTarget.dataset.type
    let order = this.data.sortOrder
    
    // 如果点击的是当前排序类型，则切换排序顺序
    if (type === this.data.sortType) {
      order = order === 'asc' ? 'desc' : 'asc'
    } else {
      // 否则设置为默认的降序
      order = 'desc'
    }
    
    this.setData({
      sortType: type,
      sortOrder: order
    })
    
    this.loadServiceList()
  },
  
  // 服务点击事件
  onServiceClick(e) {
    const serviceId = e.currentTarget.dataset.id
    // 跳转到服务详情页
    wx.navigateTo({
      url: `/pages/service/detail?id=${serviceId}`
    })
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    this.loadServiceList()
    wx.stopPullDownRefresh()
  },
  
  // 触底加载更多
  onReachBottom() {
    // 实际项目中可以在这里实现分页加载
    // this.loadMoreServices()
  }
})